<?php
/**
 * ajax接收端
 */

use extend\GoodsImage;
use lib\supply\Order;

include("./includes/fun.global.php");
include_once(SYSTEM_ROOT . "extend/GoodsCart.php");
@header('Content-Type: application/json; charset=UTF-8');

switch ($_QET['act']) {
    case 'submit_input': #提交
        $User = \login_data::user_data();
        if (!empty((int)$_QET['orders'])) {
            //启用新的订单缓存
            $DataOrder = $DB->get_row("SELECT * FROM `sky_journal` WHERE `count` = '{$_QET['orders']}' AND `name` = '订单缓存' AND `uid` = -1024 LIMIT 1");
            if (!$DataOrder) dies(-1, '订单已经失效！,请重新提交！');
            $data = config::common_unserialize($DataOrder['content'])['data'][0];
            $_QET['gid'] = $data['gid'];
            $_QET['data'] = $data['input'];
            $_QET['num'] = $data['num'];
        }

        $order = Order::Creation($_QET, $User);
        if ($order <> false) {
            dies(1, '订单创建成功,点击查看订单！');
        } else dies(-1, '订单创建失败,请联系管理员处理！');
        break;
    case 'order_details': #查询订单详情
        if (empty($_QET['id'])) die(json_encode(['code' => '-1', 'msg' => '请填写完整！']));
        $id = (int)$_QET['id'];
        $Data = HomecachingVerify($_QET['act'], $id);
        if ($Data == false) {
            $Data = Order::Query($id);
            if ($Data['code'] == 1) {
                HomecachingAdd($_QET['act'], $id, $Data);
            }
        }
        dier($Data);
        break;
    case 'OrderQuery': //查询订单（新）
        if (empty($_QET['type'])) dies(-1, '请填写完整！');
        switch ($_QET['type']) {
            case 'OrderAll':
                \query::OrderAll($_QET['msg']);
                break;
            case 'QueryList':
                \query::QueryList($_QET['msg']);
                break;
            case 'QueryMark': //提交商品评价内容
                $User = \login_data::user_data();
                \query::QueryMark($_QET, $User);
                break;
            case 'QueryTake': //确认收货
                $User = \login_data::user_data();
                \query::QueryTake($_QET['id'], $User);
                break;
            case 'QueryDelete':
                $User = \login_data::user_data();
                \query::QueryDelete($_QET['id'], $User);
                break;
        }
        break;
    case 'OrderPay': //订单付款！
        if (empty((int)$_QET['id'])) dies(-1, '请填写完整！');
        query::OrderPay($_QET['id']);
        break;
    case 'OrderDel': //删除订单
        if (empty((int)$_QET['id'])) dies(-1, '请填写完整！');
        query::OrderDel($_QET['id']);
        break;
    case 'Discuss':
        if (empty($_QET['gid']) || empty($_QET['type'])) dies(-1, '请填写完整！');
        $DB = \Medoo\DB\SQL::DB();
        $Res = $DB->select('mark', [
            '[>]user' => ['uid' => 'id']
        ], ['user.name', 'user.image(n_image)', 'mark.image', 'mark.name(describe)', 'mark.score', 'mark.addtime', 'mark.content'], ['mark.gid' => $_QET['gid'], 'mark.state' => 1]);
        switch ($_QET['type']) {
            case 'List':
                $Avg = $DB->avg('mark', 'score', ['gid' => $_QET['gid']]);
                dier([
                    'code' => 1,
                    'msg' => '评论列表获取成功',
                    'data' => $Res,
                    'avg' => $Avg,
                ]);
                break;
        }
        break;
    case 'orders_transit': #写入日志缓存！

        if (empty($_QET['conts']) || empty((int)$_QET['gid']) || empty($_QET['data'])) dies(-1, '请将参数提交完整！');
        if (empty((int)$_QET['num'])) {
            $_QET['num'] = 1;
        }

        $arr_blacklist = explode(',', $conf['blacklist']);
        foreach ($arr_blacklist as $v) {
            if (strpos(json_encode($_QET['data']), $v) !== false) dies(-1, '下单信息：<font color="red" size="5">' . $v . '</font><br>已被站长设置为下单违禁词！');
        }
        $IP = userip();
        $input = [];

        foreach ($_QET['data'] as $v) {
            $input[] = trim($v);
        }

        $Data = serialize(['data' => [['gid' => $_QET['gid'], 'input' => $input, 'num' => $_QET['num'], 'conts' => $_QET['conts']]]]);
        $count = $DB->count("SELECT count(*) FROM `sky_journal` WHERE `name` = '订单缓存' ") + 1;
        $re = $DB->query("INSERT INTO `sky_journal` (`ip`, `uid`, `count`, `name`, `content`, `date`) VALUES ('$IP', '-1024', '$count', '订单缓存', '$Data', '$date');");
        if ($re) {
            if (template::isMobile() == true) {
                $typs = 1;
                $url = '/?mod=checkstandM&order=';
            } else {
                $typs = 2;
                $url = '/?mod=checkstandPC&order=';
            }
            dier(['code' => 1, 'msg' => '订单创建成功,点击前往付款！', 'url' => $url . $count, 'type' => $typs]);
        } else dies(-1, '订单创建失败！' . $DB->error());
        break;
    case 'getclass': #获取分类
        $Data = HomecachingVerify($_QET['act'], 1);
        if ($Data == false) {
            $re = $DB->query("SELECT * FROM `sky_class` WHERE `state` = 1  ORDER BY `sort` DESC ");
            $array = [];
            while ($res = $DB->fetch($re)) {
                $count = $DB->count("SELECT count(*) FROM `sky_goods` WHERE `cid` = '{$res['cid']}' AND `state` = '1' ");
                $res['number'] = $count;
                $array[] = $res;
            }
            HomecachingAdd($_QET['act'], 1, $array);
        } else $array = $Data;
        dier([
            'code' => 0,
            'msg' => 'succ',
            'data' => $array
        ]);
        break;
    case 'SharePoster':
        if (empty((int)$_QET['gid'])) dies(-1, '请填写完整！');
        include_once(SYSTEM_ROOT . "extend/GoodsImage.php");

        $image = ($conf['share_image'] == 1 ? GoodsImage::mergePic($_QET['gid']) : GoodsImage::mergPicClouds($_QET['gid']));

        if ($image) {
            dier([
                'code' => 1,
                'msg' => '商品海报图生成成功！',
                'src' => $image . '?sr=' . time()
            ]);
        } else dies(-1, '商品海报图生成失败！');
        break;
    case 'prevent':
        if (empty($_SESSION['url_pr'])) dies(-1, '无权访问');
        $Data = HomecachingVerify($_QET['act'], $_SESSION['url_pr']);
        if ($Data == false) {
            $url_doem = str_replace("[url]", reward::prevent($_SESSION['url_pr'], 2), $conf['share_url']);
            HomecachingAdd($_QET['act'], $_SESSION['url_pr'], $url_doem);
        } else $url_doem = $Data;
        dies(1, $url_doem);
        break;
    case 'getgoods': //获取分类下的商品
        $cid = (int)$_QET['cid'];
        $name = $_QET['name'];
        if (empty($cid) && $name == 'null') dies(-1, '请填写完整');
        if ($cid == '-1') {
            if ($conf['HomePageDisplay'] == 1) {
                $Cla = $DB->get_row("SELECT * FROM `sky_class` ORDER BY `sort` DESC LIMIT 1");
                if ($Cla) $cid = $Cla['cid'];
            } else {
                $num = 18;
                $user_data = login_data::user_data();
                $Data = HomecachingVerify($_QET['act'] . $num, $user_data);
                if ($Data == false) {
                    $re = $DB->query("SELECT custom,gid,name,image,quota,sort,cid,quantity,profits,money,(SELECT count(b.gid) FROM `sky_order` as b WHERE b.gid = a.gid LIMIT 188 ) as cgid FROM `sky_goods` as a WHERE `gid` >= (SELECT floor(RAND() * (SELECT MAX(gid) FROM `sky_goods` WHERE `state` = 1 ))) AND `state` = 1 ORDER BY cgid DESC  LIMIT $num ");
                    while ($res = $DB->fetch($re)) {
                        $atl = $DB->count("SELECT sum(num) FROM `sky_buylog` WHERE `gid` = '{$res['gid']}' AND `date`> '$times' ");
                        $res['quota'] = $res['quota'] - $atl;
                        $price = price::price_uid(($user_data == false ? -1 : $user_data['grade']), $res['profits'], $res['money'], $res['custom']);
                        unset($res['profits'], $res['money']);
                        if ($price['price'] <= 0.01 && $price['price'] <> 0) $price['price'] = 0.01;
                        $res['price'] = round($price['price'], 2);
                        $res['points'] = round($price['points'], 0);
                        $res['level'] = $price['level'];
                        $array[] = $res;
                    }
                    HomecachingAdd($_QET['act'] . $num, $user_data, $array);
                } else $array = $Data;

                dier([
                    'code' => 0,
                    'msg' => '数据获取成功',
                    'data' => $array
                ]);
            }
        }

        if (empty($_QET['cid']) && $name <> 'null' && $name <> '') {
            $SQL = "SELECT gid,name,image,quota,sort,cid,quantity,profits,money,custom FROM `sky_goods` WHERE `state` = 1 AND `name` LIKE '%" . $name . "%' ORDER BY `sort` DESC ";
        } else {
            $SQL = "SELECT gid,name,image,quota,sort,cid,quantity,profits,money,custom FROM `sky_goods` WHERE `state` = 1 AND `cid`= '$cid'  ORDER BY `sort` DESC ";
        }

        $user_data = login_data::user_data();
        $Data = HomecachingVerify($_QET['act'] . $cid, $user_data);
        if ($Data == false) {
            $re = $DB->query($SQL);
            $array = [];
            while ($res = $DB->fetch($re)) {
                $atl = $DB->count("SELECT sum(num) FROM `sky_buylog` WHERE `gid` = '{$res['gid']}' AND `date`> '$times' ");
                $res['quota'] = $res['quota'] - $atl;
                $price = price::price_uid(($user_data == false ? -1 : $user_data['grade']), $res['profits'], $res['money'], $res['custom']);
                unset($res['profits'], $res['money']);
                if ($price['price'] <= 0.01 && $price['price'] <> 0) $price['price'] = 0.01;
                $res['price'] = round($price['price'], 2);
                $res['points'] = round($price['points'], 0);
                $res['level'] = $price['level'];
                $array[] = $res;
            }
        } else $array = $Data;
        dier([
            'code' => 1,
            'msg' => 'success',
            'data' => $array
        ]);
        break;
    case 'GoodsMonitoring':
        $gid = (int)$_QET['gid'];
        if (empty($gid)) dies(-1, '请填写完整');
        $gidass = $DB->get_row("SELECT * FROM `sky_goods` WHERE `gid`='$gid'  LIMIT 1");
        if (in_array(5, json_decode($gidass['method'], TRUE))) {
            $Flie = ROOT . 'includes/lib/soft/controller/CommodityPriceMonitoring/index.php';
            if (!file_exists($Flie)) dies(1, '应用未安装！');
            include_once $Flie;
            $state_gid = \lib\CommodityPriceMonitoring::origin($gidass);
            if ($state_gid == -1) {
                $user_data = login_data::user_data();
                HomecachingUnlink('getgoods_details' . $gid, $user_data);
                dies(-1, $conf['SupervisoryMsg']);
            } else dies(1, '商品价格无需调整！');
        }
        break;
    case 'getgoods_details':
        $gid = (int)$_QET['gid'];
        if (empty($gid)) dies(-1, '请填写完整');
        $user_data = login_data::user_data();
        $Data = HomecachingVerify($_QET['act'] . $gid, $user_data);
        if ($Data == false) {
            $res = $DB->get_row("SELECT custom,freight,picture,alert,gid,name,image,value,quota,quantity,docs,method,cid,profits,money,min,max FROM `sky_goods` WHERE `gid`='$gid' AND `state` = 1  LIMIT 1");
            if (!$res) dies(-1, '商品不存在,或已下架,请返回上一页！');
            $atl = $DB->count("SELECT sum(num) FROM `sky_buylog` WHERE `gid` = '{$res['gid']}' AND `date`> '$times'  ");

            if (empty($_SESSION['GIDSALES_' . $_QET['gid']])) {
                $LSALES = $conf['SalesSum'] + round(($conf['SalesSum'] * (rand(1, 50) / 100)), 0);
                $_SESSION['GIDSALES_' . $_QET['gid']] = $LSALES;
            } else $LSALES = $_SESSION['GIDSALES_' . $_QET['gid']];

            $res['sales'] = $DB->count("SELECT sum(num) FROM `sky_order` WHERE `gid` =  '{$res['gid']}'  ") + $LSALES;
            $res['count_quota'] = $res['quota'] - $atl;
            $res['count'] = count(explode('|', $res['value']));
            $res['currency'] = $conf['currency'];
            $res['method'] = json_decode($res['method'], TRUE);
            $res['docs'] = htmlspecialchars_decode(htmlspecialchars_decode($res['docs']));
            $price = price::price_uid(($user_data == false ? -1 : $user_data['grade']), $res['profits'], $res['money'], $res['custom']);
            unset($res['profits'], $res['money']);
            if ($price['price'] <= 0.01 && $price['price'] <> 0) $price['price'] = 0.01;
            $res['price'] = round($price['price'], 2);
            $res['points'] = round($price['points'], 0);
            $res['level'] = $price['level'];
            $res['level_arr'] = $price['level_arr'];
            $res['pay'] = $conf['pay_qqapy'] . '_' . $conf['pay_wxpay'] . '_' . $conf['pay_alipay'];
            if ($res['min'] == null || $res['min'] == '') $res['min'] = 0;
            if ($res['max'] == null || $res['max'] == '') $res['max'] = 0;
            if ($res['freight'] <> -1) {
                $freight = $DB->get_row("SELECT money,region,nums,exceed,threshold FROM `sky_freight` WHERE `id` = '{$res['freight']}' LIMIT 1");
                if ($freight) {
                    $res['freight'] = $freight;
                }
            }
            $res['cart_count'] = \extend\GoodsCart::CartCount();
            HomecachingAdd($_QET['act'] . $gid, $user_data, $res);
        } else $res = $Data;

        dier([
            'code' => 1,
            'msg' => 'succ',
            'data' => $res
        ]);
        break;
    case 'CartNum': //购物车下单份数修改
        \extend\GoodsCart::CartNum($_QET);
        break;
    case 'CartList': //查询购物车列表
        dier(\extend\GoodsCart::CartList($_QET['data'], $_QET['CartKey']));
        break;
    case 'CartAdd': //加入购物车
        if ($conf['CartState'] <> 1) dies(-1, '购物车功能已经关闭!');
        \extend\GoodsCart::CartAdd($_QET);
        break;
    case 'CartDet': //删除购物车指定内容
        if (!(int)isset($_QET['id'])) dies(-1, '请提交完整！');
        \extend\GoodsCart::CartDet((int)$_QET['id']);
        break;
    case 'SubmitOrder': //提交队列订单到服务器
        if (!(int)isset($_QET['id'])) dies(-1, '请提交完整！');
        Order::SubmitOrderQueue((int)$_QET['id']);
        break;
    case 'CartSkip': //跳转中转
        if (count($_QET['data']) == 0) dies(-1, '请最少选择一个购物车订单！');
        if (template::isMobile() == true) {
            $typs = 1;
            $url = '/?mod=CartCheckstandM&arr=' . xiaochu_en(json_encode($_QET['data']));
        } else {
            $typs = 2;
            $url = '/?mod=CartCheckstandPC&arr=' . xiaochu_en(json_encode($_QET['data']));
        }
        dier(['code' => 1, 'msg' => '订单创建成功,点击前往付款！', 'url' => is_https(false) . href() . $url, 'type' => $typs]);
        break;
    case 'CartPay': //结算购物车商品
        \extend\GoodsCart::CartPay($_QET['data'], (int)$_QET['type'], $_QET['mode'], $_QET['CartKey']);
        break;
    case 'GoodsRound':
        /*
         * 取出随机18条商品
         * 优先推荐下单率高的商品
         */
        if (empty((int)$_QET['num'])) {
            $num = 18;
        } else $num = $_QET['num'];

        $user_data = login_data::user_data();
        $Data = HomecachingVerify($_QET['act'] . $num, $user_data);
        if ($Data == false) {
            $re = $DB->query("SELECT custom,gid,name,image,quota,sort,cid,quantity,profits,money,(SELECT count(b.gid) FROM `sky_order` as b WHERE b.gid = a.gid LIMIT 188 ) as cgid FROM `sky_goods` as a WHERE `gid` >= (SELECT floor(RAND() * (SELECT MAX(gid) FROM `sky_goods` WHERE `state` = 1 ))) AND `state` = 1 ORDER BY cgid DESC  LIMIT $num ");
            while ($res = $DB->fetch($re)) {
                $atl = $DB->count("SELECT sum(num) FROM `sky_buylog` WHERE `gid` = '{$res['gid']}' AND `date`> '$times' ");
                $res['quota'] = $res['quota'] - $atl;
                $price = price::price_uid(($user_data == false ? -1 : $user_data['grade']), $res['profits'], $res['money'], $res['custom']);
                unset($res['profits'], $res['money']);
                if ($price['price'] <= 0.01 && $price['price'] <> 0) $price['price'] = 0.01;
                $res['price'] = round($price['price'], 2);
                $res['points'] = round($price['points'], 0);
                $res['level'] = $price['level'];
                $array[] = $res;
            }
            HomecachingAdd($_QET['act'] . $num, $user_data, $array);
        } else $array = $Data;

        dier([
            'code' => 0,
            'msg' => '数据获取成功',
            'data' => $array
        ]);
        break;
    case 'gethuoshan':
        $url = trim($_POST['url']);
        if (empty($url)) dies(-1, 'url不能为空');
        $result = gethuoshan($url);
        dier($result);
        break;
    case 'getxiaohongshu':
        $url = trim($_POST['url']);
        if (empty($url)) dies(-1, 'url不能为空');
        $result = getxiaohongshu($url);
        dier($result);
        break;
    case 'getshuoshuo':
        $uin = trim(daddslashes($_GET['uin']));
        $page = intval($_GET['page']);
        if (empty($uin)) dies(-1, 'QQ号不能为空');
        $result = getshuoshuo($uin, $page);
        dier($result);
        break;
    case 'getkuaishou':
        $url = trim($_POST['url']);
        if (empty($url)) dies(-1, 'url不能为空');
        $result = getkuaishou($url);
        dier($result);
        break;
    case 'getkuaishou2': //新快手链接
        $url = trim($_POST['url']);
        if (empty($url)) dies(-1, 'url不能为空');
        $result = getkuaishou2($url);
        dier($result);
        break;
    case 'getshareid':
        $url = trim($_POST['url']);
        if (empty($url)) dies(-1, 'url不能为空');
        $result = getshareid($url);
        dier($result);
        break;
    case 'query_goods': #查询商品
        $val = (string)$_QET['name'];
        if (empty($val)) dies(-1, '请填写完整');
        $user_data = login_data::user_data();
        $re = $DB->query("SELECT  custom,gid,name,image,quota,sort,cid,quantity,profits,money FROM `sky_goods` WHERE `state` = 1 AND `name` like '%$val%' ORDER BY `sort` DESC ");
        $array = [];
        while ($res = $DB->fetch($re)) {
            $atl = $DB->count("SELECT sum(num) FROM `sky_buylog` WHERE `gid` = '{$res['gid']}' AND `date`> '$times' ");
            $res['quota'] = $res['quota'] - $atl;
            $price = price::price_uid(($user_data == false ? -1 : $user_data['grade']), $res['profits'], $res['money'], $res['custom']);
            unset($res['profits'], $res['money']);
            if ($price['price'] <= 0.01 && $price['price'] <> 0) $price['price'] = 0.01;
            $res['price'] = round($price['price'], 2);
            $res['points'] = round($price['points'], 0);
            $res['level'] = $price['level'];
            $array[] = $res;
        }
        dier([
            'code' => 0,
            'msg' => 'succ',
            'data' => $array
        ]);
        break;
    case 'PopupNotice': //公告弹窗
        if (!empty($_SESSION['PopupNotice'])) dies(-1, '老了弹不动了');
        $content = htmlspecialchars_decode(htmlspecialchars_decode(base64_decode($conf['PopupNotice'])));
        if ($content == '' || $content == '<p><br></p>') {
            dies(-1, '未设置弹窗内容');
        } else {
            $_SESSION['PopupNotice'] = 1;
            dies(1, $content);
        }
        break;
    case 'Banner': //banner取出图片数据
        $banner = explode('|', $conf['banner']);
        $a = '';
        foreach ($banner as $v) {
            $image_url = explode('*', $v);
            $a .= '<div class=swiper-slide><a target=_blank href=' . $image_url['1'] . '><img lay-src=' . $image_url['0'] . ' style=max-height: 34vh  /></a></div>';
        }
        dier([
            'code' => 1,
            'msg' => '获取成功',
            'data' => $a,
        ]);
        break;
    default:
        dies(-1, '访问的内容不存在！');
        break;
}